package com.atguigu.spzx.manager.service.Impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.manager.mapper.SysRoleUserMapper;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.AssignRoleDto;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;


    /**
     * 用户登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public LoginVo login(LoginDto loginDto) {
        // 获取输入验证码和存储到redis的key名称  loginDto获取
        String captcha = loginDto.getCaptcha();
        String key = loginDto.getCodeKey();

        // 根据获取的redis里面key ,查询redis里面存储验证码
        String redisCode = redisTemplate.opsForValue().get("user:Validate" + key);

        // 比较输入的验证码与redis里面的验证码是否一致
        // 如果不一致,提示用户,校验失败
        if (StrUtil.isEmpty(redisCode) || !StrUtil.equalsAnyIgnoreCase(redisCode,captcha)){
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        //如果一致,删除redis里面的验证码
        redisTemplate.delete("user:Validate"+key);


        //1 获取提交用户名,loginDTO获取
        String userName = loginDto.getUserName();
        //2 根据用户名查询数据库表sys_user表
        SysUser sysUser = sysUserMapper.selectUserInfoByUserName(userName);
        //3 如果根据用户名查询不到对应的信息,用户不存在 , 返回错误信息
        if (sysUser == null) {
            // throw new RuntimeException("用户不存在!");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        //4 如果根据用户名查询到用户信息,用户存在
        //5 获取输入的密码,比较输入的密码与数据库密码是否一致
        String database_password = sysUser.getPassword();
        //将输入的密码进行加密在比较
        String input_password =
                DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());

        if (!input_password.equals(database_password)) {
            //throw new RuntimeException("密码错误!");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        //6 如果密码一致,登录成功  如果密码不一致,登录失败
        //7 登录成功,生成用户的唯一标识 token
        String token = UUID.randomUUID().toString().replaceAll("-", "");

        //8 把登录成功用户信息放到redis里面
        //key:token     value: 用户信息

        redisTemplate.opsForValue()
                .set("user:login" + token, JSON.toJSONString(sysUser),24 , TimeUnit.HOURS);

        //9  返货loginVO对象

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }

    /**
     * 获取当前登录的用户信息
     */
    @Override
    public SysUser getUserInfo(String token) {
        //获取token字符串
        String userJson = redisTemplate.opsForValue().get("user:login" + token);
        //把获取到的字符串转成SysUser对象
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return sysUser;
    }
    /**
     * 用户退出
     */
    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login"+token);
    }

    /**
     * 分页查询
     * @param sysUserDto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<SysUser> findByPage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {
        //设置分页参数
        PageHelper.startPage(pageNum,pageSize);
        //根据条件查询所有数据
        List<SysUser> list =  sysUserMapper.findByPage(sysUserDto);
        //将查询到的数据封装PageInfo对象
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);

        return pageInfo;
    }

    /**
     * 添加用户
     * @param sysUser
     */
    @Override
    public void saveSysUser(SysUser sysUser) {
        //判断用户名不能重复
        String userName = sysUser.getUserName();
        SysUser dbSysUser = sysUserMapper.selectUserInfoByUserName(userName);
        if (dbSysUser != null){
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        //输入密码进行加密
        String md5_password = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
        sysUser.setPassword(md5_password);

        //设置status值 1 可用,  2 不可用
        sysUser.setStatus(1);

        sysUserMapper.save(sysUser);
    }

    /**
     * 修改用户
     * @param sysUser
     */
    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.update(sysUser);
    }

    /**
     * 删除用户
     * @param userId
     */
    @Override
    public void deleteById(Long userId) {
        sysUserMapper.delete(userId);
    }

    /**
     * 用户分配角色
     * @param assignRoleDto
     */
    @Override
    public void doAssign(AssignRoleDto assignRoleDto) {
        //1.根据userId删除用户之前分配角色数据
        sysRoleUserMapper.deleteByUserId(assignRoleDto.getUserId());
        //2.重新分配数据
        List<Long> roleIdList = assignRoleDto.getRoleIdList();
        for (Long roleId : roleIdList) {
            sysRoleUserMapper.doAssign(assignRoleDto.getUserId(),roleId);
        }
    }
}
